/*******************************************************
 * 
 * 文件名(File Name)：             SpriteTitleChange.cs
 *
 * 作者(Author)：                  http://www.youkexueyuan.com
 *								  XiaoHong 
 *                                Yangzj
 *
 * 创建时间(CreateTime):           2016/03/02 13:49:34
 *
 *******************************************************/

using UnityEngine;
using System.Collections;
using MyFrameWork;

public class TestTimer : MonoBehaviour 
{
	private TimerBehaviour _timer;
	private string _leftTime;

	void Awake()
	{
		_timer = TimerManager.GetTimer(this.gameObject);
	}

	// Use this for initialization
	void Start () 
	{
		StartTimer(10);
	}

	private int _buffIndex = 0;
	void OnGUI()
	{
		GUI.Label(new Rect(200,240,100,40),string.Format("剩余时间:{0}",_leftTime));

		if(GUI.Button(new Rect(200,300,100,40),"add 3 sec"))
		{
			AddTimer(3);
		}
		if(GUI.Button(new Rect(200,360,100,40),"add 5 sec"))
		{
			AddTimer(5);
		}

		if(GUI.Button(new Rect(400,300,200,40),"生成一个5秒buff"))
		{
			//生成一个5秒buff，不重复生成
			string buffName = string.Format("Buff{0}",_buffIndex++);
			DebugUtil.Debug(buffName + " start");
			FrameTimerHeap.AddTimer(5*1000,0,OnBuffFinish,buffName);
		}
	}

	private void OnBuffFinish(string buffName)
	{
		DebugUtil.Debug(buffName + " finished.");
	}

	private void StartTimer(uint leftSecs)
	{
		_timer.StartTimer(leftSecs,OnEverySecCallBack,OnFinishTimer);
	}

	private void AddTimer(uint addSecs)
	{
		uint leftSecNow = (uint)_timer.GetCurrentTime();
		StartTimer(leftSecNow + addSecs);
	}
	
	
	private void OnEverySecCallBack(uint leftSecs)
	{
		DebugUtil.Info("OnEverySecCallBack -- Left Secs:" + leftSecs);
		SetLeftTime(leftSecs);
	}

	private void OnFinishTimer()
	{
		DebugUtil.Info("OnFinishTimer");

		uint leftSecs = (uint)_timer.GetCurrentTime();
		SetLeftTime(leftSecs);
//		Invoke(
	}

	private void SetLeftTime(uint leftSecs)
	{
		uint  min = (leftSecs % 3600) / 60;
		uint second = (leftSecs % 3600) % 60;
		_leftTime = string.Concat(min.ToString("d2"), ":", second.ToString("d2")); 
	}

	void OnDestroy()
	{
		_timer = null;
	}

}
